import React from 'react'
import { connect } from 'dva'
import {Form, Modal, Button, Icon, Dropdown, Menu, Row, Input, Table, Col, Radio, Select, Popconfirm} from 'antd'
import ListPage from 'widget/PageTmpl/ListPage'
import Keypress  from 'widget/Keypress'
import UserPop from 'widget/UserPop/UserPop'
import FlagBtn from 'widget/FlagBtn/FlagView'
import { mapStateToProps } from 'utils/view_utils'
import { Link, hashHistory } from 'dva/router'
import config from '../../../../config/config'
import styles from './applyStyle.less'
import {cloneDeep} from 'lodash'
import TextArea from 'antd/lib/input/TextArea'

const FormItem = Form.Item;
const Option = Select.Option;


const formItemLayout1 = {
	labelCol: { span: 9 }, wrapperCol: { span: 15 }
};
const formItemLayout2 ={
	labelCol: { span: 4 }, wrapperCol: { span: 20 }
}
const routeView = ({ dispatch, model, form }) => {

	const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
	const { modelObj, namespace } = model
	//console.log("userListModel", modelObj)
	let {showAddVisible, dataSource, actionType, modalPageData, showAuditDialog, remark, currentId } = modelObj
	const menu = (
		<Menu onClick={(e) => { againConfirmation(e.key) }}>
			<Menu.Item key="delete">批量删除</Menu.Item>
			<Menu.Item key="forbid">批量禁用</Menu.Item>
			<Menu.Item key="open">批量启用</Menu.Item>
		</Menu>
	)

	//todo:后台暂时未定，需要修改表头字段
	//弹框列表
	const columns = [
		{
			title: '', dataIndex: "radio", key: 'radio', width: 60,
			render: (text, record, index) => {
				return (<div>
					<Radio checked={record.checked} onChange={(e) => {
						let dataIndex = (modalPageData.pageNo - 1) * modalPageData.pageSize + index;
						dataSource.map((x, i) => {
              x.checked=i == dataIndex
						})
						dispatch({
							type: `${namespace}/updateStore`,
							payload: dataSource
						})
					}
					} > </Radio>
				</div>)
			}
		},
		{
			title: '企业名称', dataIndex: 'enterpriseName', key: 'enterpriseName', width: 100,
		},
		{
			title: '统一社会编号', dataIndex: 'unicode', key: 'unicode', width: 100,
		},
		{
			title: '地址', dataIndex: 'department', key: 'department', width: 100,
            render: (text, record, index ) =>{
                return record.province + record.city + record.area + record.address
            }
		},
		{
			title: '联系方式', dataIndex: 'mobile', key: 'mobile', width: 100,
		},
        {
			title: '用户名', dataIndex: 'username', key: 'username', width: 100,
		},
		{
			title: '审核状态', dataIndex: 'state', key: 'state', width: 60,
			render: (text, record, index) => {
				if(record.state == 0){
					return "未审核"
				}else if(record.state == 1){
					return "通过"
				}else if(record.state == 2){
					return "不通过"
				}else if(record.state == 3){
					return "启用"
				}else if(record.state == 4){
					return "禁用"
				}else{
					return ""
				}
			}
		},
		{ title: '审核意见', dataIndex: 'remark', key: 'remark', width: 100, },
        { title: '审核时间', dataIndex: 'auditTime', key: 'auditTime', width: 100, },
        { title: '审核人', dataIndex: 'auditMan', key: 'auditMan', width: 100, },
	]
	
	

	// 再次确认提示框
	function againConfirmation(actionType, actionId, modalTheme = 'confirm') {
		// 设置传入的参数
		const params = { accountIdList: modelObj.biz.selectedRows.map(item => item.accountId) };

		// 当为批量操作状态时，需要额外传入参数 -- 1：批量启用；2：批量禁用
		if (['forbid', 'open'].includes(actionType)) {
			params.state = actionType === 'forbid' ? 2 : 1;
		}

		// 根据当前弹出框的操作类型，设置调用的方法
		const funName = ['singleDelete', 'delete'].includes(actionType) ? 'batchDelete' : 'batchUpdate';

		// 设置提示信息，删除时的提示信息由接口返回
		const tips = actionType === 'delete' ? '删除' : actionType === 'forbid' ? `禁用` : `启用`;

		Modal[modalTheme]({
			title: '友情提示',
			content: `确定要${tips}选中的用户吗？`,
			maskClosable: true,
			okText: '确定', cancelText: '取消',
			onOk: () => {
				dispatch({ type: `${namespace}/${funName}`, payload: { params, cb: () => modelObj.biz.refreshListDatas(true) } });
			}
		})
	}
	// 刷新列表数据
	function fresh() {
		modelObj.biz.refreshListDatas(true)
	}

	function changeStatus(item) {
		let status = 1;
		if (item.state == 1) { status = 2 }
		dispatch({
			type: `${namespace}/changeStatus`,
			payload: {
				params: { accountId: item.accountId, state: status },
				cb: () => { fresh() }
			}
		})
	}



	//todo:需要修改表头字段
	function renderSearchFields() {
		let arr = [
			{
				en_name: "communityName",
				zh_name: "小区名称",
				elem_type: "Input",
				elem_valid_type: "string"
			},
			{
				en_name: "agent",
				zh_name: "代理人姓名",
				elem_type: "Input",
				elem_valid_type: "string"
			},
			{
				en_name: "mobile",
				zh_name: "代理人手机号",
				elem_type: "Input",
				elem_valid_type: "string"
			}
		];
		return arr;
	}
	//todo:需要修改表头字段
	function renderTableFields() {
		let arr = [
			{
				en_name: "communityName",
				zh_name: "小区名称",
				width:100
			},
			{
				en_name: "communityAddress",
				zh_name: "小区地址",
				width:180
			},
			{
				en_name: "building",
				zh_name: "楼栋",
				width:300
			},
			{
				en_name: "unit",
				zh_name: "单元",
				width:130
			},
			{
				en_name: "total",
				zh_name: "业主户数",
				width:130
			},
			{
				en_name: "floor",
				zh_name: "总层高",
				width:130
			},
            {
				en_name: "agent",
				zh_name: "代理人姓名",
			},
            {
				en_name: "mobile",
				zh_name: "联系方式",
				width:180,
			},
			{
				en_name: "createTime",
				zh_name: "申请时间",
				width:180,
			},];

		return arr
	}

	let pageProps = {
		ui: {
			api_url: "admin/apply/list",
			method: "POST",
			app: "",
			params: "",
			mockData: null,
			search_bar: {
				fields: renderSearchFields()
			},
			action_bar: [
				{
					func_name: "onBatDel",
					label: "批量删除",
					rowSelection: (selectedRowKeys, selectedRows) => { },
					render: () => {
						let isDisabled = true;
						if (modelObj.biz && modelObj.biz.selectedRows && modelObj.biz.selectedRows.length != 0) {
							isDisabled = false;
						}
						return (
							<Dropdown overlay={menu} disabled={isDisabled} >
								<Button style={{marginRight:'15px'}}>
									批量操作 <Icon type="down" />
								</Button>
							</Dropdown>
						)
					}
				},
				// {
				// 	func_name: "onAdd",
				// 	label: "新增",
				// 	type: "primary",
				// 	btnId:'100101',
				// 	icon: "plus",
				// 	onClick: (e) => {
				// 		dispatch({
				// 			type: `${namespace}/updateStore`,
				// 			payload: { actionType: "add", showAddVisible: true }
				// 		})

				// 		// dispatch({
				// 		// 	type: `${namespace}/getFrom4AUser`,
				// 		// 	payload: { name: '李四' }
				// 		// })
				// 	},
				// }
			],
			// 数据表格
			table: {
				fields: renderTableFields(),
				scroll: { x: 1600 },
				action_props: {
					width: 160,
					fixed: 'right',
				},
				actions: [
							{
								render: (item) => {
									if(item.state == 0){
										return <FlagBtn
											node={<a  onClick={() => doAudit(item.id, 1)}>通过</a>}
											btnId={'100102'}>
											</FlagBtn>
									}else if(item.state == 4){
										return <FlagBtn
											node={<a  onClick={() => doAudit(item.id, 3)}>启用</a>}
											btnId={'100102'}>
											</FlagBtn>
									}else{
										return <span></span>
									}
									
			
								}
							},
							{
								render: (item) => {
									return <span></span>
									
								}
							},
						]
			}
		}
	}


	function doAudit(id, type){
		let modalTheme = "confirm"
		if(type == 1){
			Modal[modalTheme]({
				title: '企业入驻审核',
				content: `确定要通过选中的企业吗？`,
				maskClosable: true,
				okText: '确定', cancelText: '取消',
				onOk: () => {
					let params = {
						"id": id,
						"state": type
					}
					dispatch({ type: `${namespace}/postAudit`, payload: { params, cb: () => modelObj.biz.refreshListDatas(true) } });
				}
			})
		}else if(type == 2){
			let params = {
				"showAuditDialog": true,
			}
			dispatch({
				type: `${namespace}/updateStore`,
				payload: {
					currentId: id,
				}
			})
			dispatch({ type: `${namespace}/updateAuditDialogState`, payload: params });
		}else if(type == 3){
			Modal[modalTheme]({
				title: '企业启用提示',
				content: `确定要启用选中的企业吗？`,
				maskClosable: true,
				okText: '确定', cancelText: '取消',
				onOk: () => {
					let params = {
						"id": id,
						"state": type
					}
					dispatch({ type: `${namespace}/banEnterprise`, payload: { params, cb: () => modelObj.biz.refreshListDatas(true) } });
				}
			})
		}else if(type == 4){
			Modal[modalTheme]({
				title: '企业禁用提示',
				content: `确定要禁用选中的企业吗？`,
				maskClosable: true,
				okText: '确定', cancelText: '取消',
				onOk: () => {
					let params = {
						"id": id,
						"state": type
					}
					dispatch({ type: `${namespace}/banEnterprise`, payload: { params, cb: () => modelObj.biz.refreshListDatas(true) } });
				}
			})
		}
	}

	function onPreparePost(){
		let params = {
			"remark": remark,
			"id": currentId,
			"state": 2
		}
		dispatch({ type: `${namespace}/postAudit`, payload: { params, cb: () => modelObj.biz.refreshListDatas(true) } });
	}

	function hideDialog(){
		dispatch({
			type: `${namespace}/updateStore`,
			payload: {
				showAuditDialog: false,
			}
		})
		fresh()
	}

	function textChange(e){
		const { value } = e.target
		dispatch({
			type: `${namespace}/updateStore`,
			payload: { remark: value }
		});
	}

	
	//数据更新
	function inputChange(name, value) {
		let obj = { [name]: value }
		detailData = Object.assign(detailData, obj)
		// console.log(detailData);
		dispatch({
			type: `${namespace}/updateStore`,
			payload: { detailData }
		});
	}
	//搜索
	function onSearch() {
		dispatch({
			type: `${namespace}/getFrom4AUser`,
			payload: {
				...detailData, cb: () => { fresh() }
			}
		});
	}
	// 分页
	const pagination = {
		onChange: changePage, //分页事件
	}
	//翻页函数
	function changePage(page, pageSize) {
		dispatch({
			type: `${namespace}/updateStore`,
			payload: {
				modalPageData: {
					pageSize: 10,
					pageNo: page
				} }
		});
		dispatch({
			type: `${namespace}/queryInfo`,
			payload: { pageNo: page, pageSize, name: detailData.name || '李四' }
		});
	}
	return <div className={styles.userList}>
    {/*监控键盘事件，自动刷新数据*/}
		{showAddVisible&&
    <Keypress keyCode={13} cbk={()=>{
      onSearch();
    }} />
		}
  
		{
			showAddVisible ? <Modal
				title={actionType == "add" ? "新增用户" : "编辑用户"}
				visible={true}
				width={1000}
				okText="确认"
				cancelText="取消"
				onOk={() => onSubmit()}
				onCancel={() => onCancel()}
			>
				{
					"add" == actionType && <div>
						<Row>
						<Col span={6}>
								<FormItem {...formItemLayout1} label="用户账号" hasFeedback>
									<Input value={detailData.uid} onChange={e => inputChange('uid', e.target.value)} />
								</FormItem>
							</Col>
							<Col span={6}>
								<FormItem {...formItemLayout1} label="姓名" hasFeedback>
									<Input value={detailData.name} onChange={e => inputChange('name', e.target.value)} />
								</FormItem>
							</Col>
							{/* <Col span={6}>

								<FormItem {...formItemLayout1} label="身份证号" hasFeedback>
									<Input value={detailData.idCardNo} onChange={e => inputChange('idCardNo', e.target.value)} />
								</FormItem>
							</Col> */}

							<Col span={6}>
								<FormItem {...formItemLayout1} label="手机号" hasFeedback>
									<Input value={detailData.mobile} onChange={e => inputChange('mobile', e.target.value)} />
								</FormItem>
							</Col>

							<Col span={6}>
								<Button type='primary' style={{ marginTop: 4, marginLeft: 32 }} onClick={() => { onSearch() }}>搜索</Button>
							</Col>

						</Row>
					</div>
				}

				<div>
					<Table columns={columns}
						dataSource={dataSource}
						pagination={pagination}
						onRow={(record, index) =>{
							return {onClick:()=> {
                  dataSource.map((x, i) => {
                    x.checked=i == index
                  })
                  dispatch({
                    type: `${namespace}/updateStore`,
                    payload: dataSource
                  })
                }}
						}}
					/>
				</div>
			</Modal> : null
		}
		<ListPage pageProps={pageProps} />
		<Modal
			visible={ showAuditDialog }
			title="企业入驻审核"
			width={600}
			okText="确认"
			cancelText="取消"
			onOk={() => onPreparePost()}
			onCancel={() => hideDialog()}
		>
			<div>
				<Row>
					<FormItem {...formItemLayout2} label="审核意见" hasFeedback>
						<TextArea rows={4} onChange={ textChange}/>
					</FormItem>
				</Row>
			</div>
		</Modal>
	</div>

}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
